/**
 * Created with Vim7.3 Mac
 * @fileOverview : 
 * @author : Lyle lylechen2014@gmail.com
 * @since : 2016-08-19 16:26:16
 * @filename : src/components/addPrivatePhoto.js
 * @version : 
 * @description : 
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  PixelRatio,
  TouchableOpacity,
  Image,
  ActivityIndicator
} from 'react-native';

let { width, height } = Utils.size;
import ImagePicker from 'react-native-image-picker';
import Tips from '../common/tips';

class AddPrivatePhoto extends Component {

    constructor(props) {
        super(props);
        this.state = {
            avatarSource: null,
            postState : false,
            uploadMsg : null,
        };
    }

   selectPhotoTapped() {
        const options = {
            quality: 0.6,
            maxWidth: 500,
            maxHeight: 500,
            allowsEditing:true,
            storageOptions: {
              skipBackup: true
            }
        };

        ImagePicker.showImagePicker(options, (response) => {
              console.log('Response = ', response);
              if (response.didCancel) {
                console.log('User cancelled photo picker');
              } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
              } else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
              } else {
                let source,imgName;
                imgName = response.uri.split('/').pop();
                // You can display the image using either:
                source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true ,imgName:imgName};
                this.setState({
                    avatarSource: source,
                    uploadMsg: null,
                });
                //this.uploadPhoto(source);
              }
        });
    }

    uploadPhoto() {
        if (this.state.avatarSource && !this.state.postState) {
          let userObj = JSON.parse(Store.session_user_id),
              photoList = userObj.private_pictures;
          if (photoList.length >= 26) {
              let obj = {type: 'error', msg: Lang.addPhoto_max_photo};
              this.refs['tips'].showTips(obj);
              this.setState({
                  avatarSource: null,
                  postState: false,
                  uploadMsg: null,
              });
        } else {
            let formData = new FormData(),that=this,
                file = this.state.avatarSource;
            this.setState({postState: true});
            formData.append('file', {uri: file.uri, name:file.imgName,type: 'image/jpeg'});
            //formData.append("about", about);
            formData.append("album_type", 11);
            Share.fetchControl({
                 url : Config.APIURL + 'common_upload_img',
                 fetchOptions : {
                     method: 'POST',
                     headers: {
                        'Content-Type': 'multipart/form-data'
                     },
                     body: formData,
                 },
                 callback : function(response) {
                    //console.log(response);
                    that.setState({
                        avatarSource: null,
                        postState: false,
                        uploadMsg: response.msg ? response.msg : 'Photo uploaded! Keep uploading other photos!',
                    }); 
                    that.editUserInfoCache(response);
                    setTimeout(function(){
                        if (that.state.uploadMsg) {
                            that.setState({
                                 uploadMsg: null,
                            });  
                        }
                    },5000);
                 }
            })
          }
      }
    }

    editUserInfoCache(response) {
        if(response.status_code == 0){
            let userObj = JSON.parse(Store.session_user_id);
            userObj.private_pictures.push(response);
            Share.setStorage('session_user_id', JSON.stringify(userObj),function(bool){
                if (bool) {
                    Share.notifyResponder('photo');
                }
            });
        } 
    }

    getText() {
        let jsx = null;
        if (this.state.uploadMsg) {
            jsx = <View style={styles.error}>
                    <Text style={styles.errorText}>
                        {this.state.uploadMsg}
                    </Text>
                  </View>
        }
        return (jsx);
    }

    render() {
        return (
          <View style={styles.container}>
              <View style={styles.photoBox}>
                <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
                  <View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}>
                  { this.state.avatarSource === null ? <Text>Select a Photo</Text> :
                    <Image style={styles.avatar} source={this.state.avatarSource} />
                  }
                  </View>
                </TouchableOpacity>
              </View>
             {this.getText()}
              <TouchableOpacity onPress={()=>this.uploadPhoto()} activeOpacity = {1} >
                  <View style={[styles.buttonView,{backgroundColor:this.state.avatarSource?'#56ade0':'#ccc'}]}>
                      {this.state.postState ? <ActivityIndicator size="small" color="#fff"/> :
                       <Text style={styles.button}> Upload </Text>
                      }
                  </View>
              </TouchableOpacity>
              <Text style={styles.textDes}>Note: Lewd, offensive, nude, copyrighted, child alone, racist and other photos prohibited by law or our Service Agreement are not allowed.</Text>
          </View>
        );
      }

}

const styles = StyleSheet.create({

  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
    padding:10,
  },

  photoBox: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    height:180,
  },

  avatarContainer: {
    borderColor: '#9B9B9B',
    borderWidth: 1 / PixelRatio.get(),
    justifyContent: 'center',
    alignItems: 'center',
    borderStyle: 'dashed',
  },
  
  avatar: {
    width: 100,
    height: 100
  },

  buttonView: {
    borderRadius:5,
    height:40,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom:5,
  },

  button: {
    color:'#fff',
    fontSize:16,
  },

  textDes: {
    color:'#999',
    fontSize:12,
    height:50,
  },

  error:{
    justifyContent: 'center',
    alignItems: 'center',
  },

  errorText: {
    height:40,
    color:'#333',
  }

});

export default AddPrivatePhoto;

